package com.yls.except.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;



public class UpImg {
	private static final String accessKeyId = "gSPTsUVkRUYyuB9Z";
	private static final String accessKeySecret = "bvuEBLgelgIr40uJ5jDCxoSiLhQx1B";
	private static final String bucketName = "youpao";
	private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
	private static final String path = "http://youpao.oss-cn-hangzhou.aliyuncs.com/";

	/**
	 * 
	 * @param outputWidth
	 *            输出宽度
	 * @param outputHeight
	 *            输出高度
	 * @param file
	 *            文件类型
	 * @return
	 */

	// 图片压缩
	public static ByteArrayInputStream CompressionImg(int outputWidth,
			int outputHeight, File file) {
		int newWidth;
		int newHeight;
		ByteArrayOutputStream out = null;
		ByteArrayInputStream in = null;
		try {
			Image img = ImageIO.read(file);
			// 为等比缩放计算输出的图片宽度及高度
			double rate1 = ((double) img.getWidth(null)) / (double) outputWidth
					+ 0.1;
			double rate2 = ((double) img.getHeight(null))
					/ (double) outputHeight + 0.1;
			// 根据缩放比率大的进行缩放控制（等比缩放）
			double rate = rate1 > rate2 ? rate1 : rate2;
			newWidth = (int) (((double) img.getWidth(null)) / rate);
			newHeight = (int) (((double) img.getHeight(null)) / rate);
			BufferedImage tag = new BufferedImage((int) newWidth,
					(int) newHeight, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(
					img.getScaledInstance(newWidth, newHeight,
							Image.SCALE_SMOOTH), 0, 0, null);
			out = new ByteArrayOutputStream();
			ImageIO.write(tag, "jpg", out);
			in = new ByteArrayInputStream(out.toByteArray());// 输入流
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return in;
	}

	/**
	 * 
	 * @param key
	 *            上传到阿里云的保存目录
	 * @param in
	 *            上传的文件流
	 * @return 文件保存在阿里云的地址
	 */

	// 上传图片到AliOss
	public static String UpImgToAlisOss(String key, InputStream in) {
		try {
			// 初始化OSSClient
			OSSClient client = new OSSClient(endpoint, accessKeyId,
					accessKeySecret);
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(in.available());
			// 上传Object.
			PutObjectResult result = client
					.putObject(bucketName, key, in, meta);
			// 打印ETag
			System.out.println(result.getETag());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path + key;
	}

	/**
	 * 
	 * @param uploadFileName
	 *            文件名
	 * @return true 表示全部是jpg的图片。false至少有一个不是jpg图片
	 */
	// 判断上传图片是否是jpg
	public static Boolean FileIsorJpg(String uploadFileName) {
		String[] FileName = uploadFileName.split(",");
		for (int i = 0; i < FileName.length; i++) {
			String houzhui = FileName[0]
					.substring(FileName[0].lastIndexOf("."));
			if (!".jpg".equals(houzhui)) {
				return false;
			}
		}
		return true;
	}

	// 图片压缩
	public static ByteArrayInputStream CompressionImg(int outputWidth,
			int outputHeight, MultipartFile mf) {
		CommonsMultipartFile cf = (CommonsMultipartFile) mf;
		DiskFileItem fi = (DiskFileItem) cf.getFileItem();
		File f = fi.getStoreLocation();
		int newWidth;
		int newHeight;
		ByteArrayOutputStream out = null;
		ByteArrayInputStream in = null;
		try {
			Image img = ImageIO.read(f);
			// 为等比缩放计算输出的图片宽度及高度
			double rate1 = ((double) img.getWidth(null)) / (double) outputWidth
					+ 0.1;
			double rate2 = ((double) img.getHeight(null))
					/ (double) outputHeight + 0.1;
			// 根据缩放比率大的进行缩放控制（等比缩放）
			double rate = rate1 > rate2 ? rate1 : rate2;
			newWidth = (int) (((double) img.getWidth(null)) / rate);
			newHeight = (int) (((double) img.getHeight(null)) / rate);
			BufferedImage tag = new BufferedImage((int) newWidth,
					(int) newHeight, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(
					img.getScaledInstance(newWidth, newHeight,
							Image.SCALE_SMOOTH), 0, 0, null);
			out = new ByteArrayOutputStream();
			ImageIO.write(tag, "jpg", out);
			in = new ByteArrayInputStream(out.toByteArray());// 输入流
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return in;
	}
}
